package com.unitd.frame.sso.common.util;

import com.unitd.frame.sso.common.encrypt.MD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @desc 验证浏览器基本信息
 * @filename BaseEntity.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016-10-12
 */
public class BrowserUtil {

	private static final Logger logger = LoggerFactory.getLogger(BrowserUtil.class.getName());

	/**
	 * @desc 混淆浏览器版本信息,获取浏览器客户端信息签名值
	 * @param request http请求对象
	 * @param value 浏览器USER-AGENT
	 * @return
	 */
	public static String getUserAgent(HttpServletRequest request, String value) {
		StringBuilder sb = new StringBuilder();
		sb.append(value).append("-").append(request.getHeader("user-agent"));
		logger.info("浏览器信息:" + sb.toString());

		// 将浏览器信息进行MD5加密
		return MD5.toMD5(sb.toString());
	}

	/**
	 * @desc 判断请求浏览器是否合法(只校验客户端信息不校验domain)
	 * @param request http请求对象
	 * @param value
	 * @param userAgent
	 * @return
	 */
	public static boolean isLegalUserAgent(HttpServletRequest request, String value, String userAgent) {
		// 获取浏览器客户端信息签名值
		String agent = getUserAgent(request, value);

		if (agent.equalsIgnoreCase(userAgent)) {
			logger.info("浏览器的userAgent是合法的,通过getUserAgent方法获取浏览器的userAgent为["+agent+"]");
			return true;
		}
		logger.info("浏览器的userAgent是非法的,通过getUserAgent方法获取浏览器的userAgent为["+agent+"]");
		return false;
	}
}